package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

/**
 * 环检测
 * @author: xiao1.wang
 * @date: 2022/6/19 13:36
 */
public class CycleDetection1 {

    private Graph G;
    private boolean hasCycle;
    private boolean[] visited;

    public CycleDetection1(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];
        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                if (dfs(i, i)) {
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    private boolean dfs(int v, int p) {
        visited[v] = true;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            } else {
                if (p != w) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean hasCycle() {
        return hasCycle;
    }

    public static void main(String[] args) {
        String filename = CycleDetection1.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CycleDetection1 cycleDetection = new CycleDetection1(g);
        System.out.println(cycleDetection.hasCycle());

        String filename2 = CycleDetection1.class.getClassLoader().getResource("g2.txt").getPath();
        Graph g2 = new Graph(filename2);
        CycleDetection1 cycleDetection2 = new CycleDetection1(g2);
        System.out.println(cycleDetection2.hasCycle());
    }
}
